// 记录管理模块 - 负责记录的UI展示和交互
import { deleteRecord } from './data.js';
import { escapeHtml } from './utils.js';

// 显示消息提醒
function showMessage(message, type = 'info') {
  const modal = document.getElementById('pic-text-x-modal');
  if (!modal) return;

  // 创建消息元素
  const messageElement = document.createElement('div');
  messageElement.className = `message-toast message-${type}`;
  messageElement.textContent = message;
  
  // 添加样式
  Object.assign(messageElement.style, {
    position: 'fixed',
    top: '60px',
    left: '50%',
    transform: 'translateX(-50%)',
    backgroundColor: type === 'success' ? '#f0f9ff' : '#fef0f0',
    color: type === 'success' ? '#409eff' : '#f56565',
    padding: '10px 20px',
    borderRadius: '4px',
    boxShadow: '0 2px 12px 0 rgba(0, 0, 0, 0.1)',
    zIndex: '2147483647',
    fontSize: '14px',
    textAlign: 'center',
    transition: 'opacity 0.3s, transform 0.3s',
    opacity: '1',
    maxWidth: '80%',
    wordWrap: 'break-word'
  });

  // 添加到弹窗中
  modal.appendChild(messageElement);

  // 3秒后自动移除消息
  setTimeout(() => {
    messageElement.style.opacity = '0';
    messageElement.style.transform = 'translateX(-50%) translateY(-20px)';
    setTimeout(() => {
      if (messageElement.parentNode) {
        messageElement.parentNode.removeChild(messageElement);
      }
    }, 300);
  }, 3000);
}

// 复制文本到剪贴板的兼容性函数
async function copyToClipboard(text) {
  try {
    // 首先尝试使用现代的Clipboard API
    if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function' && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    } else {
      // 降级到传统的document.execCommand方法
      const textArea = document.createElement('textarea');
      textArea.value = text;
      
      // 避免滚动到底部
      textArea.style.top = '0';
      textArea.style.left = '0';
      textArea.style.position = 'fixed';
      textArea.style.opacity = '0';
      
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      
      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);
      
      return successful;
    }
  } catch (err) {
    console.error('复制失败:', err);
    // 即使出现异常，也尝试使用传统方法作为最后的备选
    try {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      
      // 避免滚动到底部
      textArea.style.top = '0';
      textArea.style.left = '0';
      textArea.style.position = 'fixed';
      textArea.style.opacity = '0';
      
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      
      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);
      
      return successful;
    } catch (fallbackErr) {
      console.error('备选复制方法也失败了:', fallbackErr);
      return false;
    }
  }
}

export function addRecordToUI(record) {
  const recordsContainer = document.querySelector('.records');
  if (!recordsContainer) return;

  const div = document.createElement('div');
  div.className = 'record-item';
  div.dataset.id = record.id;

  // 新的界面布局
  div.innerHTML = `
    <div class="record-header">
      <div class="record-filename">${escapeHtml(record.fileName)}</div>
      <div class="record-actions">
        <button class="btn-icon btn-copy" title="复制">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M4 2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V2zm2 0v6h6V2H6zm-2 9a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-3zm2 1v2h8v-2H6z"/>
          </svg>
        </button>
        <button class="btn-icon btn-download" title="下载">
          <svg width="16" height="16" viewBox="-2 -1 19 20" fill="currentColor">
            <path d="M8 12l-5-5 1.41-1.41L7 8.17V0h2v8.17l2.59-2.58L13 7l-5 5zm-6 4h12v2H2v-2z"/>
          </svg>
        </button>
        <button class="btn-icon btn-delete" title="删除">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm0 14a6 6 0 1 1 0-12 6 6 0 0 1 0 12zM5.354 5.646a.5.5 0 0 0-.708.708L7.293 9l-2.647 2.646a.5.5 0 0 0 .708.708L8 9.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 9l2.647-2.646a.5.5 0 0 0-.708-.708L8 8.293 5.354 5.646z"/>
          </svg>
        </button>
      </div>
    </div>
    <div class="record-text">${escapeHtml(record.text)}</div>
    <div class="record-footer">
      <div class="record-time">${escapeHtml(record.time)}</div>
      <div class="record-source">${escapeHtml(record.source)}</div>
    </div>
  `;

  div.querySelector('.btn-copy').addEventListener('click', async () => {
    if (record.text.length > 200) {
      showMessage('文字超过200字，建议下载查看', 'info');
    } else {
      try {
        const success = await copyToClipboard(record.text);
        if (success) {
          showMessage('已复制到剪贴板', 'success');
        } else {
          // 提供手动复制的提示
          const textArea = document.createElement('textarea');
          textArea.value = record.text;
          textArea.style.position = 'fixed';
          textArea.style.top = '-1000px';
          document.body.appendChild(textArea);
          textArea.select();
          showMessage('请按 Ctrl+C 复制文本', 'info');
          document.body.removeChild(textArea);
        }
      } catch (err) {
        console.error('复制失败:', err);
        showMessage('复制失败，请手动复制', 'error');
      }
    }
  });

  div.querySelector('.btn-download').addEventListener('click', () => {
    const blob = new Blob([record.text], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    
    // 使用图片名+时间戳作为文件名
    const fileNameWithoutExtension = record.fileName.replace(/\.[^/.]+$/, ""); // 去除扩展名
    const timestamp = record.id; // 使用记录ID作为时间戳
    const downloadFileName = `PicTextX_${fileNameWithoutExtension}_${timestamp}.txt`;
    
    const a = document.createElement('a');
    a.href = url;
    a.download = downloadFileName;
    a.click();
    URL.revokeObjectURL(url);
    showMessage('文件已开始下载', 'success');
  });

  div.querySelector('.btn-delete').addEventListener('click', () => {
    div.remove();
    deleteRecord(record.id);
    showMessage('记录已删除', 'success');
  });

  recordsContainer.prepend(div);
}